<template>
  <div class="exam-container">
    <el-descriptions title="安排考试" direction="vertical" :column="2" border>
      <el-descriptions-item label="名称" :span="1">
        <el-input placeholder="在此输入此次考试名称" v-model="name"></el-input>
      </el-descriptions-item>

      <el-descriptions-item label="选择试卷" :span="1">
        <div style="display: flex; justify-content: space-between">
          <el-tag type="danger" v-if="testpaper == '' || testpaper == null">暂未选择</el-tag>
          <el-tag type="primary" v-else
            >{{ testpaper.name }}.{{ testpaper.lv }}星.{{ testpaper.count }}题</el-tag
          >
          <el-button type="warning" size="small" plain @click="selectTestpaper">去选择</el-button>
          <el-dialog v-model="dialogTableVisible_Testpaper" title="选择试卷">
            <el-skeleton :loading="isFirst" :rows="10" animated>
              <el-table :data="testpaper_data" v-loading="isLoad" :border="true">
                <el-table-column label="序号" type="index" width="60px" />
                <el-table-column property="name" label="试卷名" width="200" />
                <el-table-column property="lv" label="难度" />
                <el-table-column property="count" label="题目" />
                <el-table-column property="labels" label="标签" />
                <el-table-column property="useCount" label="使用" />
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      :loading="btnLoad"
                      @click="select_testpaper(scope.row)"
                      >选择</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div
                style="
                  margin-top: 10px;
                  padding-bottom: 10px;
                  display: flex;
                  justify-content: space-between;
                  border: 1px solid #eee;
                "
              >
                <el-pagination
                  background
                  layout="prev, pager, next,total"
                  :total="testpaper_total"
                  small
                  style="margin: 10px 0 0 10px"
                  v-model:current-page="testpaper_page"
                />
              </div>
            </el-skeleton>
          </el-dialog>
        </div>
      </el-descriptions-item>

      <el-descriptions-item label="考试时间" :span="1">
        <el-date-picker
          v-model="beginTime"
          type="datetime"
          placeholder="选择考试开始时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="x"
        />
      </el-descriptions-item>

      <el-descriptions-item label="考试时长(5分钟-7天)" :span="1">
        <el-input-number :min="5" :max="10080" style="width: 100%" v-model="endTime">
        </el-input-number>
      </el-descriptions-item>

      <el-descriptions-item label="选择组织" :span="1">
        <div style="display: flex; justify-content: space-between">
          <el-tag type="danger" v-if="organization.length == 0">暂未选择</el-tag>
          <el-tag type="primary" v-else>{{ organization_name }}</el-tag>
          <el-button type="warning" size="small" plain @click="selectOrg">去选择</el-button>
        </div>
        <!-- :default-expanded-keys="[2, 3]"
                :default-checked-keys="[5]" -->
        <el-dialog v-model="dialogTableVisible_org" title="选择组织">
          <el-skeleton :loading="org_isFirst" :rows="10" animated>
            <div style="margin: 0 6px 5px 6px; border: 1px solid #eee">
              <el-tree
                :data="o_data"
                show-checkbox
                node-key="id"
                default-expand-all
                :props="defaultProps"
                check-strictly
                :default-checked-keys="organization_id"
                @check="check_change"
                ref="getCheck_org"
              >
              </el-tree>
            </div>
            <el-button
              type="primary"
              style="margin-left: 8px; margin-top: 5px"
              @click="oK_org"
              :disabled="o_button == true"
              >确定</el-button
            >
          </el-skeleton>
        </el-dialog>
      </el-descriptions-item>

      <el-descriptions-item label="描述(选填)" :span="1">
        <el-input type="textarea" v-model="explain"></el-input>
      </el-descriptions-item>

      <el-descriptions-item label="" :span="2">
        <el-button
          type="primary"
          size="medium"
          @click="addArrange"
          :disabled="
            name == '' ||
            testpaper == '' ||
            beginTime == '' ||
            beginTime == null ||
            organization.length == 0
          "
          >新增</el-button
        >
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watchEffect, ref, onMounted } from 'vue'
import getTime from '@/utils/getTime'
import { getTestPapers } from '../../../api/testpaper'
import { getOrganizations, AddArrange } from '../../../api/arrange'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import type {arrange_addDto,data_testpaper} from '../../../dto/exam/arrange/addDto'
import { openLoad, closeLoad } from '@/utils/loading'
export default defineComponent({
  setup() {
    const getCheck_org = ref('');
    const router=useRouter();
    /**
     * 组织复选框配置
     */
    const defaultProps = {
      children: 'children',
      label: 'name',
      id: 'id'
    }
    const data = reactive<arrange_addDto>({
      dialogTableVisible_org: false,
      dialogTableVisible_Testpaper: false,
      isLoad: false,
      isFirst: true,
      org_isFirst: true,
      name: '',
      tpid: '',
      beginTime: '',
      endTime: 10,
      explain: '',
      testpaper: '',
      o_data: [],
      organization: [],
      organization_id: [],
      organization_name: '',
      o_button: true
    })

    /**
     * 选择试卷参数
     */
    const data_testpaper = reactive<data_testpaper>({
      testpaper_data: [],
      testpaper_page: 1,
      testpaper_limit: 5,
      testpaper_total: 0,
      testpaper_isPublish: 1,
      testpaper_isBan: 0
    })

    const events = {
      /**
       * 组织列表复选框改变事件 暂时用于组织列表确认按钮的监听
       */
      check_change: () => {
        console.log(getCheck_org.value)

        if (getCheck_org.value.getCheckedNodes().length != 0) {
          data.o_button = false
        } else {
          data.o_button = true
        }
      },
      /**
       * 选择试卷的选择按钮
       */
      select_testpaper: (val: any) => {
        data.testpaper = val
        data.dialogTableVisible_Testpaper = false
      },
      /**
       * 试卷的对话框的显示
       */
      selectTestpaper: () => {
        data.dialogTableVisible_Testpaper = true
        data.isLoad = true
        getTestPapers({
          page: data_testpaper.testpaper_page,
          limit: data_testpaper.testpaper_limit,
          isPublish: data_testpaper.testpaper_isPublish,
          isBan: data_testpaper.testpaper_isBan
        }).then((res: any) => {
          data_testpaper.testpaper_data = res.data.data
          data_testpaper.testpaper_total = res.data.total
          data.isFirst = false
          data.isLoad = false
        })
      },
      /**
       * 组织弹框确定按钮
       */
      oK_org: () => {
        data.organization = getCheck_org.value.getCheckedNodes();
        /**
         * 选中的组织名称赋值
         */
        data.organization_name = data.organization.map((d: any) => d.name)
        data.organization_name = data.organization_name.join(',');
        //选择的组织id存放
        data.organization_id = data.organization.map((d: any) => d.id);

        data.dialogTableVisible_org = false;
      },
      /**
       * 选择组织 组织按钮点击事件触发
       */
      selectOrg: () => {
        data.dialogTableVisible_org = true;
        data.org_isFirst = true;
        if (data.organization_id.length != 0) {
          data.o_button = false;
        }
        /**
         * 获取组织列表
         */
        getOrganizations({ page: 1, limit: 9999 }).then((res: any) => {
          if (res.result === 0) {
            data.o_data = res.data.data;
            data.org_isFirst = false;
          }
        })
      },
      /**
       * 添加安排试卷
       */
      addArrange: () => {
        //离考试结束至少有5分钟
        let nowTime = getTime.timestampToTime(new Date().getTime() + 5 * 60 * 1000);
        //考试结束时间
        let endTime = getTime.timestampToTime(data.beginTime + data.endTime * 60 * 1000);
        //考试开始时间
        let beginTime = getTime.timestampToTime(data.beginTime);
        if (endTime < nowTime) {
          ElMessage.error('考试结束时间离现在最少要5分钟');
          return
        }
        //组织id
        let orgids = data.organization_id.join(",");
        //试卷id
        let tpid = data.testpaper.id;
        ElMessageBox.confirm("确认为安排考试吗？").then((res:any)=>{
                openLoad("请稍后");
                AddArrange({
                beginTime: beginTime,
                endTime:endTime,
                explain: data.explain,
                name: data.name,
                orgids: orgids,
                tpid: tpid
              }).then((res: any) => {
                closeLoad();
                  if(res.result===0){
                         ElMessage.success("操作成功");
                         router.go(-1);
                  }else{
                         ElMessage.success(res.message);
                  }
              })
        }).catch(()=>{})
    
      }
    }

    onMounted(() => {
      if (data.organization_id.length != 0) {
        data.o_button = false
      }
    })

    watchEffect(() => {
      if (data.dialogTableVisible_Testpaper == true) {
        events.selectTestpaper()
      } else {
        data_testpaper.testpaper_page = 1
      }
    })

    return {
      ...toRefs(data),
      ...events,
      ...toRefs(data_testpaper),
      defaultProps,
      getCheck_org
    }
  }
})
</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 400px;
}
.el-input {
  width: 400px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
